/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * LoginScreen.java
 *
 * Created on Mar 24, 2011, 10:13:24 AM
 */

package org.libarae.client;

import java.net.SocketTimeoutException;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import org.libarae.client.threads.LoginThread;
import org.libarae.communication.ClientInterface;
import org.libarae.communication.request.ServerPingRequest;
import org.libarae.communication.response.Response;

/**
 *
 * @author Ben
 */
@SuppressWarnings("serial")
public class LoginScreen extends javax.swing.JFrame {
	LoginThread mLoginThread = null;

    /** Creates new form LoginScreen */
    public LoginScreen() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblTitle = new javax.swing.JLabel();
        lblServerSelector = new javax.swing.JLabel();
        cboServerSelector = new javax.swing.JComboBox();
        sepLoginCenter = new javax.swing.JSeparator();
        lblUsername = new javax.swing.JLabel();
        txtUsername = new javax.swing.JTextField();
        lblPassword = new javax.swing.JLabel();
        btnSubmit = new javax.swing.JButton();
        btnNewUser = new javax.swing.JButton();
        txtPassword = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Libarae");
        setIconImage(new ImageIcon(getClass().getResource("/res/icon.png")).getImage());
        setLocationByPlatform(true);
        setResizable(false);

        lblTitle.setFont(new java.awt.Font("Tahoma", 0, 36));
        lblTitle.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblTitle.setLabelFor(this);
        lblTitle.setText("Libarae");

        lblServerSelector.setLabelFor(cboServerSelector);
        lblServerSelector.setText("Server:");

        cboServerSelector.setEditable(true);
        cboServerSelector.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "127.0.0.1" }));
        cboServerSelector.setToolTipText("Please type in your server address or find it in the list.");
        cboServerSelector.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));

        sepLoginCenter.setOrientation(javax.swing.SwingConstants.VERTICAL);

        lblUsername.setLabelFor(txtUsername);
        lblUsername.setText("Username:");

        lblPassword.setLabelFor(txtPassword);
        lblPassword.setText("Password:");

        btnSubmit.setText("Submit");
        btnSubmit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSubmitActionPerformed(evt);
            }
        });

        btnNewUser.setText("New User");
        btnNewUser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewUserActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtUsername, javax.swing.GroupLayout.DEFAULT_SIZE, 175, Short.MAX_VALUE)
                            .addComponent(lblUsername)
                            .addComponent(lblPassword)
                            .addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 175, Short.MAX_VALUE)
                            .addComponent(btnSubmit, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addComponent(sepLoginCenter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnNewUser, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(lblServerSelector)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cboServerSelector, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(69, 69, 69))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(lblTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cboServerSelector, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblServerSelector))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(13, 13, 13)
                            .addComponent(btnNewUser, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(sepLoginCenter, javax.swing.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(27, 27, 27)
                        .addComponent(lblUsername)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(lblPassword)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnSubmit)))
                .addGap(27, 27, 27))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    // Send a LoginRequest to the server. If it's successful, switch to MainScreen.
    private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSubmitActionPerformed
    	ClientInterface.setServerAddress(cboServerSelector.getSelectedItem().toString());
    	
    	mLoginThread = new LoginThread(this, txtUsername.getText(), new String(txtPassword.getPassword()));
    	mLoginThread.run();
    }//GEN-LAST:event_btnSubmitActionPerformed

    // Ping the server and open up the NewUserScreen if it's responsive.
    private void btnNewUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewUserActionPerformed
        ClientInterface.setServerAddress(cboServerSelector.getSelectedItem().toString());
        ServerPingRequest r = new ServerPingRequest();
        
        
        Response response = null;
        
        try{
            response = ClientInterface.sendRequest(r);
        }
        catch(SocketTimeoutException e)
        {
            JOptionPane.showMessageDialog(null, "Request timed out. Please try again.");
            return;
        }
        catch(Exception e)
        {
            //e.printStackTrace();
        }
        
        if(response == null)
        {
            JOptionPane.showMessageDialog(this, "No server running at that address.");
            return;
        }

        if(response.getStatus() == Response.STATUS_GOOD)
        {
            NewUserScreen nu = new NewUserScreen(cboServerSelector.getSelectedItem().toString());

            nu.setVisible(true);
            this.dispose();
        }
    }//GEN-LAST:event_btnNewUserActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        try {
                // Set System L&F
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch (UnsupportedLookAndFeelException e) {
           // handle exception
            System.err.println("Unable to set look and feel.");
            System.err.println(e.getMessage());
            System.exit(1);
        }
        catch (ClassNotFoundException e) {
           // handle exception
            System.err.println("Unable to set look and feel.");
            System.err.println(e.getMessage());
            System.exit(1);
        }
        catch (InstantiationException e) {
           // handle exception
            System.err.println("Unable to set look and feel.");
            System.err.println(e.getMessage());
            System.exit(1);
        }
        catch (IllegalAccessException e) {
           // handle exception
            System.err.println("Unable to set look and feel.");
            System.err.println(e.getMessage());
            System.exit(1);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new LoginScreen().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnNewUser;
    private javax.swing.JButton btnSubmit;
    private javax.swing.JComboBox cboServerSelector;
    private javax.swing.JLabel lblPassword;
    private javax.swing.JLabel lblServerSelector;
    private javax.swing.JLabel lblTitle;
    private javax.swing.JLabel lblUsername;
    private javax.swing.JSeparator sepLoginCenter;
    private javax.swing.JPasswordField txtPassword;
    private javax.swing.JTextField txtUsername;
    // End of variables declaration//GEN-END:variables

}
